<?php

namespace app\service;

use app\common\BaseService;
use app\model\Goods as GoodsModel;

class GoodsService extends BaseService {
  public static function getInstance(): GoodsService {
    return parent::getInstance();
  }

  public static function getModel(): GoodsModel {
    return GoodsModel::getInstance();
  }

  /*
   * 列表
   */
  public static function getGoodsList($condition, $page, $pageSize = 30, $order = ['id' => 'desc']) {
    return self::getModel()->getDataDetail($condition, $page, $pageSize, $order);
  }

  /*
   * 分页
   */
  public static function getGoodsPager($condition, $page, $pageSize = 30) {
    return self::getModel()->pager($condition, $page, $pageSize);
  }

  /*
   * 通过condition获取goods
   */
  public function getGoodsByCondition($conditions, $order = ['id' => 'DESC']) {
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $result = $query->order($order)->select()->toArray();
    return $result;
  }

  /*
   * 获取所有数据
   */
  public static function getAllGoods($conditions, $order) {
    $result = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $result = $result->where($field, $op, $value);
    }
    if ($order) {
      $result = $result->order($order);
    }
    return $result->select()->toArray();
  }

  /*
   * 批量新增商品
   */
  public static function createGoodsMulti($store, $isAdd) {
    $data = $store['productList'];
    $gys = $store['gys'];
    $date = $store['date'];
    // 新增到goods
    $insert = [];
    // 返回提示信息
    $msg = '';
    // 查看是否有相同 名称-规格的商品
    $houseRes = HouseService::getModel()
      ->select()
      ->toArray();
    $houseList = [];
    foreach ($houseRes as $v) {
      $str = $v['productn'].'-'.$v['model'];
      $houseList[$str] = $v;
    }
    // 循环商品
    foreach ($data as $value) {
      $str = $value['productn'].'-'.$value['model'];
      $house = [];
      if (isset($houseList[$str])) {
        $house = $houseList[$str];
        // 查询仓库是否添加已有的商品
        if (!$isAdd) {
          $msg .= '商品:“' . $house['productn'] . '” 规格:“' . $house['model'] . '” 单位:“' . $house['unit'] . '” 类型:“'.$house['product'].'”；';
        }
      }
      $insert[] = [
        'date' => $date,
        'product' => isset($house['product']) ? $house['product'] : $value['product'],
        'productn' => isset($house['productn']) ? $house['productn'] : $value['productn'],
        'model' => isset($house['model']) ? $house['model'] : $value['model'],
        'amoumt' => $value['amoumt'],
        'unit' => isset($house['unit']) ? $house['unit'] : $value['unit'],
        'price' => $value['price'],
        'housecost' => 0,
        'total' => $value['total'],
        'paid' => $value['paid'],
        'notpaid' => $value['total'] - $value['paid'],
        'inhouse' => 0,
        'other' => $value['other'],
        'installtime' => isset($value['installtime']) ? $value['installtime'] : null,
        'js' => $value['js'],
        'gys' => $gys,
      ];
    }
    if ($msg && !$isAdd) {
      return ['status' => true, 'msg' => $msg];
    }
    $res = self::getModel()->saveAll($insert);
    if ($res) {
      return ['status' => true, 'msg' => 'ok'];
    }
    return ['status' => false, 'msg' => '新增失败'];
  }

  /*
   * 新增商品
   */
  public static function createGoods($house_id, $data) {
    // 获取商品库存
    $house = HouseService::getModel()->find($house_id)->toArray();
    $insert = [
      'date' => $data['date'],
      'product' => $house['product'],
      'productn' => $house['productn'],
      'model' => $house['model'],
      'amoumt' => $data['newamoumt'],
      'unit' => $house['unit'],
      'price' => $data['price'],
      'housecost' =>$house['nowcost'],
      'total' => $data['total'],
      'paid' => $data['paid'],
      'notpaid' => $data['total'] - $data['paid'],
      'inhouse' => 0,
      'other' => $data['other'],
      'installtime' => isset($value['installtime']) ? $data['installtime'] : null,
      'js' => $data['js'],
      'gys' => $data['gys']
    ];
    $res = self::getModel()->save($insert);
    if ($res) {
      return ['status' => true, 'msg' => 'ok'];
    }
    return ['status' => false, 'msg' => '新增失败'];
  }

  /*
   * 修改
   */
  public static function updateGoods($id, $data) {
    $notpaid = $data['total'] - $data['paid'] > 0 ? $data['total'] - $data['paid'] : 0;
    $data = [
      'date' => $data['date'],
      'paid' => $data['paid'],
      'notpaid' => round($notpaid, 2),
      'other' => $data['other'],
      'installtime' => $data['installtime'],
      'js' => $data['js'],
      'gys' => $data['gys']
    ];
    self::getModel()
      ->where('id', $id)
      ->update($data);
    return ['status' => true, 'msg' => 'ok'];
  }

  /*
   * 删除
   */
  public static function deleteGoods($id) {
    $res = self::getModel()
      ->where('id', $id)
      ->delete();
    if (!$res) {
      return ['status' => false, 'msg' => '删除失败'];
    }
    return ['status' => true, 'msg' => 'ok'];
  }

  /*
   * 入库
   */
  public static function confirmGoods($id) {
    // 获取采购数据
    $goods = self::getModel()->find($id)->toArray();
    $model = $goods['model'];
    // 通过采购数据的规格 获取相同规格的仓库数据
    $house = HouseService::getModel()
      ->where('model', '=', $model)
      ->find();
    // 更新house
    $updateHouse = [];
    // 更新goods
    $updateGoods = [];
    // 新增house
    $insertHouse = [];

    // 如果有仓库数据
    if ($house) {
      $house = $house->toArray();
      $houseId = $house['id'];
      // 成本 = 总价/数量
      // $nowcost = (现成本 * (可销售库存 + 旧品库存+待出库库存+待出库旧品库存) + 入库数量 * 采购单价)/(可销售库存 + 旧品库存+待出库库存+待出库旧品库存+入库数量)
      $nowcost = ($house['nowcost'] * ($house['amoumt'] + $house['oldamoumt'] + $house['wamoumt'] + $house['oldwamoumt']) + ($goods['amoumt'] * $goods['price'])) / ($house['amoumt'] + $house['oldamoumt'] + $house['wamoumt'] + $house['oldwamoumt'] + $goods['amoumt']);
      // 更新仓库数据
      $updateHouse = [
        'amoumt' => $house['amoumt'] + $goods['amoumt'],
        'nowcost' => round($nowcost, 2)
      ];
    // 如果没有仓库数据
    } else {
      // 新增仓库数据
      $insertHouse = [
        'product' => $goods['product'],
        'productn' => $goods['productn'],
        'model' => $goods['model'],
        'unit' => $goods['unit'],
        'amoumt' => $goods['amoumt'],
        'wamoumt' => 0,
        'oldamoumt' => 0,
        'oldwamoumt' => 0,
        'badamoumt' => 0,
        'nowcost' => $goods['price'],
      ];
    }
    // 更新采购单
    $updateGoods = [
      'inhouse' => 1,
      'installtime' => date('Y-m-d H:i:s')
    ];
    self::getModel()->startTrans();
    try {
      if ($updateHouse) {
        $res = HouseService::getModel()
          ->where('id', $houseId)
          ->update($updateHouse);
        if (!$res) {
          throw new \Exception('修改house失败');
        }
      }
      if ($updateGoods) {
        $res1 = self::getModel()
          ->where('id', $id)
          ->update($updateGoods);
        if (!$res1) {
          throw new \Exception('修改goods失败');
        }
      }
      if ($insertHouse) {
        $res2 = HouseService::getModel()->insert($insertHouse);
        if (!$res2) {
          throw new \Exception('新增house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 撤销入库
   */
  public static function cancelGoods($id) {
    // 获取采购数据
    $goods = self::getModel()->find($id)->toArray();
    $model = $goods['model'];
    // 通过采购数据的规格 获取相同规格的仓库数据
    $house = HouseService::getModel()
      ->where('model', '=', $model)
      ->find()
      ->toArray();
    $houseId = $house['id'];
    // 更新goods
    $updateGoods = [];

    // 当前数量：可售数量 + 旧品 + 待出货 + 待出货旧品
    $count  = $house['amoumt'] + $house['oldamoumt'] + $house['wamoumt'] + $house['oldwamoumt'];
    // 修改的可售数量：
    if ($house['amoumt']-$goods['amoumt'] < 0) {
      return ['status' => false, 'msg' => '库存不足'];
    }
    $amoumt = $house['amoumt'] - $goods['amoumt'];
    // 当前总价
    $total = $house['nowcost'] * $count;
    // 修改后的总价 = (成本*数量) - (入库数量*采购单价)
    $newTotal = $total-($goods['amoumt'] * $goods['price']) > 0 ? $total-($goods['amoumt'] * $goods['price']) : 0;
    // 更新house
    $updateHouse = [
      'amoumt' => $amoumt,
      'nowcost' => $amoumt ? round(($newTotal / $amoumt), 2) : 0
    ];
    self::getModel()->startTrans();
    try {
      if ($updateHouse) {
        $res = HouseService::getModel()
          ->where('id', $houseId)
          ->update($updateHouse);
        if (!$res) {
          throw new \Exception('修改house失败');
        }
      }
      $res1 = self::getModel()
        ->where('id', $id)
        ->update(['inhouse' => 0]);
      if (!$res1) {
        throw new \Exception('修改goods失败');
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }
}